import React, { useEffect, useRef, useState } from 'react';
import { Tabs, Dropdown } from 'antd';
import { useNavigate, useLocation } from 'react-router-dom';
import styles from "./tabs.module.scss";
import { mobxState } from '@/data';
import { toJS } from 'mobx';
import { observer } from 'mobx-react-lite';
import { useAliveController } from 'react-activation';
import { getRouteInfo } from '@/router';

const FrameHeaderTabComponent = () => {
    const location = useLocation();
    const { dropScope } = useAliveController();
    const navigate = useNavigate();
    const onChange = (newActiveKey) => {

    };

    const onClickTab = ({ key, path, label, state }) => {

        navigate(path, { state: state });

    }

 

    /**
     * @description 传入一个key，获取它上一个，和下一个的key，以及去掉它的tabs数组，返回一个新的tabs数组。
     */
    const getTabsForFilterThis = (clickKey) => {
        const keyOfIndex = toJS(mobxState.tabs).findIndex((item) => item.key === clickKey);


        let previousTab = null;
        let nextTab = null;

        const newTabs = toJS(mobxState.tabs).filter((item) => item.key !== clickKey);
        if (toJS(mobxState.tabs)[keyOfIndex - 1]) {
            previousTab = toJS(mobxState.tabs)[keyOfIndex - 1] || null;
        }
        if (toJS(mobxState.tabs)[keyOfIndex + 1]) {
            nextTab = toJS(mobxState.tabs)[keyOfIndex + 1] || null;
        }


        return {
            newTabs,
            clickKey: clickKey,
            previousTab,
            nextTab
        }
    };



    /**
     * @description 要移除一个tab，判断当前要移除的是不是当前激活的？是激活的，则激活上一个tab，否则直接关闭,
     * @param } targetKey 
     * @param {*} actionType 
     */
    const remove = (targetKey, actionType) => {

        const { newTabs,
            clickKey: clickKey,
            previousTab,
            nextTab } = getTabsForFilterThis(targetKey);

        //如果当前激活的和点击关闭的是同个，则判断有没有下一个nextTab？有的话，使用nextTab的key来激活；没有的话，使用previousTab的key来激活；都没有的话，则不激活任何tab。
        if (mobxState.activeTabKey === targetKey) {
            nextTab ?
                navigate(nextTab.path, { state: nextTab.state })
                : previousTab &&
                navigate(previousTab.path, { state: previousTab.state })
        } else {
            //不是同一个不用切换激活
        }
        mobxState.setTabs(newTabs);
        targetKey && dropScope(targetKey); //清除了缓存
    };
    const onEdit = (targetKey, action) => {

        if (toJS(mobxState.tabs).length <= 1) {

        } else {
            remove(targetKey, action);
        }
    };






    //右键菜单相关功能 start
    const [triggerRecord, setTriggerRecord] = useState(null);

    //查找当前path菜单在tabs中的索引
    const findIndex = (path) => {
        let index = -1;
        toJS(mobxState.tabs).forEach((item, i) => {
            if (item.path === path) {
                index = i;
            }
        })
        return index;
    }

    /**
     * @description 判断是否禁用按钮(关闭左侧，右侧，其他)
    
     * @param {*} param0 
     * @returns 
     */
    const judegDisabled = ({ index, type }) => {
        const length = toJS(mobxState.tabs).length;
        if (type === "right") {
            return length - 1 <= index ? true : false;
        } else if (type === "left") {
            return index > 0 ? false : true;
        } else {
            return true;
        }
    }

    //关闭左侧，把mobxState.tabs中的Index小于index的都删除掉
    const closeLeft = (index,path) => {
        const list = [];
        toJS(mobxState.tabs).forEach((item, i) => {
            if (i >= index || item.key === mobxState.activeTabKey) {
                list.push(item)
            }
        })
        mobxState.setTabs(list)
    }
    const closeRight = (index) => {
        const list = [];
        toJS(mobxState.tabs).forEach((item, i) => {
            if (i <= index || item.key === mobxState.activeTabKey) {
                list.push(item)
            }
        })
        mobxState.setTabs(list)
    }

    //关闭其他
    const closeOther = (index) => {
        const list = [];
        toJS(mobxState.tabs).forEach((item, i) => {
            if (item.key === mobxState.activeTabKey || index === i) {
                list.push(item)
            }

        })
        mobxState.setTabs(list)
    }



    const menuItems = [
        {
            label: '关闭当前',
            key: '1',
            disabled: toJS(mobxState.tabs).length <= 1 ? true : false,
            onClick: () => {
                remove(triggerRecord?.key, "remove");
            }
        },
        {
            label: '关闭其他',
            key: '2',
            disabled: toJS(mobxState.tabs).length <= 1 ? true : false,
            onClick: () => {
                closeOther(findIndex(triggerRecord?.path))

            }
        },
        {
            label: '关闭左侧',
            key: '3',
            disabled: judegDisabled({ index: findIndex(triggerRecord?.path), type: "left" }),
            onClick: () => {
                closeLeft(findIndex(triggerRecord?.path),triggerRecord?.path)
            }
        },
        {
            label: '关闭右侧',
            key: '4',
            disabled: judegDisabled({ index: findIndex(triggerRecord?.path), type: "right" }),
            onClick: () => {
                closeRight(findIndex(triggerRecord?.path))
            }
        },
    ]

    const onOpenChange = (open, info, item) => {
        if (open) {
            setTriggerRecord(item)
        } else {
            setTriggerRecord(null)
        }

    }

    const TabPanelLabel = ({ item }) => {

        return <Dropdown
            menu={{ items: menuItems }}
            trigger={['contextMenu']}
            onOpenChange={(open, info) => {
                onOpenChange(open, info, item)
            }}
        >
            <div onClick={() => onClickTab(item)}>{item.label}</div>
        </Dropdown>
    }



    //高亮某个tab 根据传入的pathname值
    const hightLightTabForPath = (location) => {
        const { pathname } = location;
        if (pathname === "/") {
            navigate("/home")
            return;

        }
        //当前pathname是否在mobxState.tabs中？
        const tab = toJS(mobxState.tabs).find((item) => item.path === pathname);
        const route = getRouteInfo(pathname); //拿到路由信息
        if (tab) {
            //存在 设置激活高亮
            mobxState.setActiveTab(tab.key)
        } else {
            //不存在

            //把route信息组成tab信息到mobxState.tabs中
            // console.log("不存在，拿到route",route)
            mobxState.addTabs({
                label: route.menuName,
                key:route.id,
                path: pathname,
                closable: true,
                state: {}
            })
            //设置激活高亮
            mobxState.setActiveTab(route.id)
        }
    }


    //根据Url来决定高亮哪个Tab（先判断是否存在，不存在则添加该项到mobxState.tabs中）
    useEffect(() => {
        hightLightTabForPath(location)
    }, [location])


    return (
        <div className={styles.tabs}
        >
            {
                (mobxState.activeTabKey && mobxState.tabs.length > 0) ? <Tabs
                    hideAdd
                    type="editable-card"
                    onChange={onChange}
                    activeKey={mobxState.activeTabKey}
                    onEdit={onEdit}
                    items={toJS(mobxState.tabs).map(item => {
                        return ({
                            ...item,
                            label: TabPanelLabel({ item: item })
                        })
                    })}

                /> : null
            }

        </div>

    );
}

export default observer(FrameHeaderTabComponent);